<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="项目名称：">
							<el-input v-model="transferVal2" placeholder="请输入项目名称" />
						</el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('ExpenseLedger1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('ExpenseLedger7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="projectName" label="项目名称" align="center" >
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="projectName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.projectName }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="180" :show-overflow-tooltip="true" prop="annualInvestmentFunds" label="全年计划投入（万元）" align="center" />
										<el-table-column min-width="200" :show-overflow-tooltip="true" prop="availableBudget" label="项目可用预算金额（万元）" align="center" />
										<el-table-column min-width="140" :show-overflow-tooltip="true" prop="completedContent" label="已完成的内容" align="center" />
										<el-table-column min-width="140" :show-overflow-tooltip="true" prop="unfinishedContent" label="未完成的内容" align="center" />
										<el-table-column min-width="100" :show-overflow-tooltip="true" prop="briefly" label="简述" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.product_Description">{{ scope.row.product_Description }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="备注" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
										<el-table-column min-width="200" :show-overflow-tooltip="false" label="操作" align="center" fixed="right">
											<el-table-column min-width="200" :show-overflow-tooltip="false" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button @click="detailHandle(scope.row)" class="icon-e" icon="ele-View" size="small" text type="success"> 详情 </el-button>
														<el-button v-if="$hasPer('ExpenseLedger2:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('ExpenseLedger3:create')" size="small" @click="documentClick(scope.row)" text type="primary"> 附件管理 </el-button>
														<el-button v-if="$hasPer('ExpenseLedger4:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form  label-width="140px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="ProjectName" label="项目名称">
							<el-input v-model="ruleForm.ProjectName" placeholder="项目名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="AnnualInvestmentFunds" label="全年计划投入">
							<el-input v-model="ruleForm.AnnualInvestmentFunds" placeholder="全年计划投入（万元）" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="AvailableBudget" label="项目可用预算金额">
							<el-input v-model="ruleForm.AvailableBudget" placeholder="项目可用预算金额（万元）" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="CompletedContent" label="已完成的内容">
							<el-input type="textarea" v-model="ruleForm.CompletedContent" placeholder="已完成的内容" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="UnfinishedContent" label="未完成的内容">
							<el-input type="textarea" v-model="ruleForm.UnfinishedContent" placeholder="未完成的内容" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="Briefly" label="简述">
							<el-input type="textarea" v-model="ruleForm.Briefly" placeholder="简述" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="Remark" label="备注">
							<el-input type="textarea" v-model="ruleForm.Remark" placeholder="备注" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 详情 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDetailDialogVisible" title="详情" width="50%" @close="cancelDetailClick">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-descriptions min-width="120px" class="margin-top" :column="2" border>
				<el-descriptions-item>
					<template #label> ID </template>
					{{ tableData.n_Id }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 项目名称 </template>
					{{ tableData.projectName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 全年计划投入（万元） </template>
					{{ tableData.annualInvestmentFunds }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label> 项目可用预算金额（万元） </template>
					{{ tableData.availableBudget }}
				</el-descriptions-item>
				<el-descriptions-item :span="2">
					<template #label> 已完成的内容 </template>
					{{ tableData.completedContent }}
				</el-descriptions-item>

				<el-descriptions-item :span="2">
					<template #label> 未完成的内容 </template>
					{{ tableData.unfinishedContent }}
				</el-descriptions-item>
				<el-descriptions-item :span="2">
					<template #label> 简述 </template>
					{{ tableData.briefly }}
				</el-descriptions-item>

				<el-descriptions-item :span="2">
					<template #label> 备注 </template>
					{{ tableData.remark }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label> 创建时间 </template>
					{{ tableData.createdTime }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 更新时间 </template>
					{{ tableData.updatedTime }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 创建人 </template>
					{{ tableData.createdUserName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 更新人 </template>
					{{ tableData.updatedUserName }}
				</el-descriptions-item>
			</el-descriptions>
			<el-divider content-position="left"> 附件查看 </el-divider>
			<el-table :data="tableData.v_FilePath" border style="width: 100%">
				<el-table-column type="index" label="序号" width="60" align="center" />
				<!-- <el-table-column prop="path" label="文件路径" min-width="120" :show-overflow-tooltip="true" align="center" /> -->
				<el-table-column prop="createdTime" label="创建时间" min-width="120" :show-overflow-tooltip="true" align="center" />
				<el-table-column prop="createdUserName" label="创建人" min-width="120" :show-overflow-tooltip="true" align="center" />
				<el-table-column label="操作" min-width="120" :show-overflow-tooltip="true" align="center">
					<template #default="scope">
						<el-button @click="viewClick(scope.row)" class="icon-e" text type="success">预览</el-button>
                                <el-button @click="downClick(scope.row)" class="icon-e" text
                                    type="warning">下载</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
		<!-- 附件上传 -->
		<uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick" @controlFileClick="controlFileClick" @updateData="getData" />
	</div>
</template>

<script lang="ts" setup>
import uploadFile from '/@/views/sms/component/reviseUploadFile.vue';
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { getSafetyPlanApi, deleteSafetyPlanApi, editSafetyPlanApi, addSafetyPlanApi, getSafetyPlanDetailApi } from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { sysFileInfoPreviewBase64 } from '/@/api/centerControl/pubilc';
import { exportToExcel } from '/@/utils/exportToExcel';
/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal2 = ref();
const searchClick = () => {
	// searchObj.ProjectName = transferVal2.value;

    let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

const resetClick = () => {
	// transferVal2.value = '';
    searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/***** 新增 编辑 弹窗 *****/
//表单及校验
const ruleFormRef = ref();
const ruleForm = reactive({
	ProjectName: '', //项目名称
	AnnualInvestmentFunds: '', //全年计划投入（万元
	AvailableBudget: '', //项目可用预算金额（万元）
	CompletedContent: '', //已完成的内容
	UnfinishedContent: '', //未完成的内容
	Briefly: '', //简述
	Remark: '', //备注
});
const rules = reactive({
	ProjectName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	AnnualInvestmentFunds: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
	],
	AvailableBudget: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
	],
	CompletedContent: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	UnfinishedContent: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
// 新增
const showDialogVisible = ref(false);
const addNodeClick = async () => {
	showDialogVisible.value = true;
};
//编辑
const saveId = ref(0);
const nodeClick = async (row: any) => {
	if (row.n_Id) {
		saveId.value = row.n_Id;

		ruleForm.ProjectName = row.projectName; //项目名称
		ruleForm.AnnualInvestmentFunds = row.annualInvestmentFunds; //全年计划投入（万元
		ruleForm.AvailableBudget = row.availableBudget; //项目可用预算金额（万元）
		ruleForm.CompletedContent = row.completedContent; //已完成的内容
		ruleForm.UnfinishedContent = row.unfinishedContent; //未完成的内容
		ruleForm.Briefly = row.briefly; //简述
		ruleForm.Remark = row.remark; //备注
	}
	showDialogVisible.value = true;
};

/***** 新增和编辑表单提交和取消事件 *****/
//取消
const cancelUseClick = () => {
	showDialogVisible.value = false;
	saveId.value = 0;
	ruleForm.ProjectName = ''; //项目名称
	ruleForm.AnnualInvestmentFunds = ''; //全年计划投入（万元
	ruleForm.AvailableBudget = ''; //项目可用预算金额（万元）
	ruleForm.CompletedContent = ''; //已完成的内容
	ruleForm.UnfinishedContent = ''; //未完成的内容
	ruleForm.Briefly = ''; //简述
	ruleForm.Remark = ''; //备注
	ruleFormRef.value!.clearValidate();
};
//确定
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				editSafetyPlanApi({ ...ruleForm, id: saveId.value });
			} else {
				addSafetyPlanApi(ruleForm);
			}
			setTimeout(() => {
				cancelUseClick();
				getData();
			}, 100);
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** detailHandle 查看详情事件 */
const showDetailDialogVisible = ref(false);
const tableData = ref();
const detailHandle = async (item: any) => {
	const res = await getSafetyPlanDetailApi({ id: item.n_Id });
	console.log(res);
	tableData.value = res.data;
	showDetailDialogVisible.value = true;
};

const cancelDetailClick = () => {
	showDetailDialogVisible.value = false;
};

/***** 删除事件 *****/
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteSafetyPlanApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

// 附件上传
/*** 附件管理 */
const fileInfo = ref();
const fileDialog = ref(false);
const cancelFileClick = () => {
	fileDialog.value = false;
};
const controlFileClick = () => {
	fileDialog.value = false;
};
const documentClick = (val: any) => {
	console.log(val, 'val');
	val.sourceType = 10;
	val.sourceId = val.n_Id;
	val.titleCon = '附件上传';
	fileInfo.value = JSON.stringify(val);
	fileDialog.value = true;
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'projectName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'ProjectName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '项目名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

/*** viewClick 文件预览 */
const baseUrl = import.meta.env.VITE_API_URL;
const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;
const viewClick = async (val: any) => {
	let viewUrl = baseUrl + '/' + val.path;
	window.open(viewUrl);
};
/*** downClick 下载文件 */
const downClick = async (val: any) => {
	let getFile = getFileFun(val.id);
	// 等待getFileFun完成
	await getFile;
	if (getFile && getFile.then) {
		getFile.then((res) => {
			let base64Data = res;
			let blob = base64ToBlob(base64Data);

			// 创建可下载的链接
			let url = URL.createObjectURL(blob);
			let link = document.createElement('a');
			link.href = url;
			link.download = val.fileOriginName; // 指定下载的文件名

			// 将链接添加到DOM中
			document.body.appendChild(link);

			// 触发点击事件开始下载
			link.click();

			// 释放临时URL
			URL.revokeObjectURL(url);
		});
	}
};
/*** getFileFun 获取文件数据 */
const getFileFun = async (val: Number) => {
	let param: any = {};
	param.id = val;
	let res: any = await sysFileInfoPreviewBase64(param);
	console.log(res, 'res');
	if (res.success) {
		return res.data;
	}
};
// 将Base64编码数据转换为Blob对象的辅助函数
const base64ToBlob = (base64Data: any) => {
	var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
	var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], { type: mimeString });
};

  /*** ================================= 导出数据函数操作 ================================= */
  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['项目名称'] = item.projectName ? item.projectName : '-';
                        tableObj['全年计划投入（万元）'] = item.annualInvestmentFunds ? item.annualInvestmentFunds : '-';
						tableObj['项目可用预算金额（万元）'] = item.availableBudget ? item.availableBudget : '-';
                        tableObj['已完成的内容'] = item.completedContent ? item.completedContent : '-';
                        tableObj['未完成的内容'] = item.unfinishedContent ? item.unfinishedContent : '-';
                        tableObj['简述'] = item.briefly ? item.briefly : '-';
                        
						tableObj['备注'] = item.remark ? item.remark : '-';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'安全生产费用台账.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getSafetyPlanApi, {}, searchObj);

onMounted(async () => {initInfoFun()});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
